package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.R;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public R findPage(Integer page, Integer pageSize) {
        // 分页查询
        IPage<Category> p = new Page<>(page, pageSize);
        //  根据sort排序
        LambdaQueryWrapper<Category> warpper = new LambdaQueryWrapper<>();
        warpper.orderByAsc(Category::getSort);

        IPage<Category> pageSelect = this.page(p, warpper);
        return R.success(pageSelect);
    }

    /**
     * 删除分类 注意: 菜品分类和套餐分类内有菜品和套餐时 是不能直接删除的
     */
    @Override
    public R deleteById(Long id) {

        LambdaQueryWrapper<Dish> warpper1 = new LambdaQueryWrapper<>();
        warpper1.eq(Dish::getCategoryId, id);
        List<Dish> dishes = dishMapper.selectList(warpper1);
        if (dishes.size() > 0) {
            // 说明菜品分类内有菜品
            return R.error("此菜品分类内有菜品不能删除");
        }

        LambdaQueryWrapper<Setmeal> warpper2 = new LambdaQueryWrapper<>();
        warpper2.eq(Setmeal::getCategoryId, id);
        List<Setmeal> setmeals = setmealMapper.selectList(warpper2);
        if (setmeals.size() > 0) {
            // 说明套餐分类内有菜品
            return R.error("此套餐分类内有套餐不能删除");
        }
        categoryMapper.deleteById(id);
        return R.success("删除成功");
    }

    @Override
    public R findList(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        if (type != null) {
            wrapper.eq(Category::getType, type);
        }
        List<Category> categories = categoryMapper.selectList(wrapper);
        return R.success(categories);
    }
}
